<template>
  <div id="printBarcodePre">
    <Breadcrumb content="预制条码打印" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="16">
          <vxe-form :data="newForm" class-name="padding-sm width-100-percentage" title-width="80px">
            <vxe-form-item title="病历号" field="patNo" class-name="width-100-percentage" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.patNo" placeholder="病历号" class-name="width-100-percentage" clearable
                  @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="病历号前缀" :item-render="{}" field="beforePatNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.beforePatNo" placeholder="病历号前缀" class-name="width-100-percentage" clearable
                  @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请号" :item-render="{}" field="reqNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.reqNo" placeholder="申请号" class-name="width-100-percentage" clearable
                  @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="床号" :item-render="{}" field="bedNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.bedNo" placeholder="床号" class-name="width-100-percentage" clearable
                  @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage">
              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[
                { title: '编码', props: 'code' }, //列标题
                { title: '名称', props: 'name' }
              ]" :title="'点击选择病人来源'" :searchParam="{ code: 'PATTYPE' }" @selectDataRow="SelectRowClick"
                :inputWidth="'100%'" v-model="newForm.patTypeName" :placeholder="'选择病人来源'" @clearValue="clearPatTypeName"
                @sliceValue="sliceHandler" />
              <!-- </template> -->
            </vxe-form-item>

            <vxe-form-item title="科室" :item-render="{}" field="deptNa" class-name="width-100-percentage">
              <!-- <template #default="{ row }">
                                <span>{{ formatItemNameByIds(row) }}</span>
                            </template> -->
              <!-- <template #edit="{ rowIndex }"> -->
              <SelectDataCheckedList :url="'/api/sys/getDepartmentList'" :column="[
                { field: 'code', title: '科室编码' }, //列标题
                { field: 'name', title: '科室名称' }
              ]" :searchParam="{ orgId }" :isPage="false" @SelectCellClick="(e) => {
  selectRow(e, rowIndex);
}
  " :clickRowId="deptIds" :showField="'name'" :inputWidth="'100%'">
              </SelectDataCheckedList>
              <!-- </template> -->
              <!-- <template #default="{ data }">
                                <vxe-input v-model="data.patNa" placeholder="姓名" class-name="width-100-percentage" clearable
                                    @keyup="keyupEnter" />
                            </template> -->
            </vxe-form-item>

            <vxe-form-item title="姓名" :item-render="{}" field="patNa" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.patNa" placeholder="姓名" class-name="width-100-percentage" clearable
                  @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="身份证号" :item-render="{}" field="IDNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input ref="refInputIDNo" v-model="data.IDNo" placeholder="身份证号" class-name="width-100-percentage"
                  @keyup.enter.native="IDNoValueChangeEnter" clearable />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[始]" :item-render="{}" field="reqDateS" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[始]" v-model="data.reqDateS" type="datetime" class-name="width-100-percentage"
                  transfer />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[止]" :item-render="{}" field="reqDateE" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[止]" v-model="data.reqDateE" type="datetime" class-name="width-100-percentage"
                  transfer />
              </template>
            </vxe-form-item>
          </vxe-form>
        </Pane>
        <Pane size="84">
          <Splitpanes horizontal>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <vxe-input v-model="newForm.searchValue" placeholder="请输入关键字" clearable
                      @clear="findPrintBarcodeSpecList()" @keyup="keyupEnter"></vxe-input>
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-search"
                      class-name="text-blue" content="查询" @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-paste" class-name="text-green"
                      class="button-blue margin-left-sm" content="读卡" @click="IdNoFocus"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-print" class-name="text-orange"
                      class="button-blue margin-left-sm" content="打印"
                      @click="printManyStep1('printBarcodePreTable')"></vxe-button>
                    <!-- <vxe-button type="text" icon="vxe-icon-print" class-name="text-orange" content="测试插入申请项目" @click="testInsertAppItem"></vxe-button> -->
                    <!-- <vxe-button type="text" icon="vxe-icon-maximize" class-name="text-olive" content="重新打印" @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete-fill" class-name="text-red" content="删除" @click="findPrintBarcodeSpecList"></vxe-button> -->
                    <vxe-checkbox v-model="isPrintZYD" class="margin-left-xs">打印回执单</vxe-checkbox>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom"
                      @dblclick="setCurComputerCheckedisPrintZYD">待打印条码申请</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodePreTable"
                :style="{ height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px)' }">
                <vxe-table ref="printBarcodePreTable" v-loading="loading" class="mytable-scrollbar" border height="auto"
                  align="left" :menu-config="tableMenuTop" :cell-style="cellStyle" :cell-class-name="cellClassName"
                  @checkbox-change="checkboxStateChange" @cell-click="printBarcodePreRowClick"
                  :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{
                    trigger: 'click',
                    mode: 'cell',
                    showStatus: false,
                    showIcon: false
                  }" :mouse-config="{ selected: true }" :keyboard-config="demo1.tableKeyboardConfig" resizable
                  show-overflow :scroll-y="{ enabled: true, gt: 50 }" show-footer :footer-method="footerMethodTop"
                  :sort-config="{ defaultSort: { field: 'sameSpecCodeBgColor', order: 'asc' } }" :data="printBarcodeList"
                  :merge-footer-items="[{ row: 0, col: 1, rowspan: 1, colspan: 5 }]">
                  <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: red" class="vxe-icon-warnion-circle-fill" v-if="row.isCatch"></span>
                      <span class="margin-left-xs" v-if="row.isCatch">{{ row.isCatch ? row.catchMessage : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="isUrgent" title="急" width="26" align="center">
                    <template #default="{ row }">
                      <span>{{ row.isUrgent ? '是' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="合" field="sameSpecCodeBgColor" sortable :sort-type="'string'" width="30"
                    align="center">
                    <template #header>
                      <span class="text-xs">合</span>
                    </template>
                    <template #default="{ row }">
                      <span class="margin-left-xs" v-if="row.isEnSameBg">&nbsp;</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="reqNo" title="条码号" width="95px" :edit-render="{ autofocus: '.vxe-input--inner' }">
                    <template #edit="{ row }">
                      <vxe-input v-model="row.reqNo" @keydown="reqNoEnter($event, row)"></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="patType" title="病人类型" width="75px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="60px"></vxe-column>
                  <vxe-column field="sex" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="50px"></vxe-column>
                  <vxe-column field="reqDept" title="科室" width="80px"></vxe-column>
                  <vxe-column field="sampleType" title="样本类型代码" width="100"></vxe-column>
                  <vxe-column field="feeName" title="申请项目名称" width="280"></vxe-column>
                  <vxe-column field="bedNo" title="床号" width="50px"></vxe-column>
                  <vxe-column field="reqTime" title="申请日期" min-width="120"></vxe-column>
                  <vxe-column field="applicantId" title="申请号" width="120"></vxe-column>
                  <vxe-column field="reqDoctor" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
                  <vxe-column field="amount" title="数量" width="60"></vxe-column>
                  <vxe-column field="price" title="金额" width="60"></vxe-column>
                  <vxe-column field="adviceGroupId" title="医嘱分组Id" width="100"></vxe-column>
                  <vxe-column field="adviceId" title="医嘱Id" min-width="100"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <vxe-input v-model="newForm.searchValue" placeholder="请输入关键字" clearable
                      @clear="newForm.searchValue = ''"
                      @keyup.enter.native="afterPrintBarcodeSpecList.filter((data) => data.patNo.contains(newForm.searchValue) || data.patNa.contains(newForm.searchValue) || data.idNo.contains(newForm.searchValue) || data.reqNo.contains(newForm.searchValue))"></vxe-input>
                    <vxe-button type="text" icon="vxe-icon-print" class-name="text-green" content="重新打印"
                      class="button-blue margin-left-sm" @click="printAgain"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete" class-name="text-red"
                      class="button-blue margin-left-sm" content="清空已打印" @click="deleteAllAfterPrintSpecs"></vxe-button>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom">已打印条码</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodePreTable" :style="{
                height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px - 8px)'
              }">
                <vxe-table ref="afterPrintBarcodeSpecTable" v-loading="afterloading" class="mytable-scrollbar" border
                  height="auto" align="center" :menu-config="tableMenuBottom" :cell-style="cellStyle"
                  :checkbox-config="{ range: true }" :cell-class-name="cellClassName" :data="afterPrintBarcodeSpecList"
                  @checkbox-change="afterCheckboxStateChange" :row-config="{ isCurrent: true, isHover: true }"
                  :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }"
                  resizable show-overflow :scroll-y="{ enabled: true, gt: 50 }">
                  <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: red" class="vxe-icon-warnion-circle-fill" v-if="row.isCatch"></span>
                      <span class="margin-left-xs" v-if="row.isCatch">{{ row.isCatch ? row.catchMessage : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="isUrgent" title="急" width="26" align="center">
                    <template #default="{ row }">
                      <span>{{ row.isUrgent ? '是' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="合" field="sameSpecCodeBgColor" width="26" align="center">
                    <template #header>
                      <span class="text-xs">合</span>
                    </template>
                    <template #default="{ row }">
                      <span class="margin-left-xs" v-if="row.isEnSameBg">&nbsp;</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="reqNo" title="条码号" width="95px"></vxe-column>
                  <vxe-column field="patType" title="病人类型" width="75px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="60px"></vxe-column>
                  <vxe-column field="sex" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="50px"></vxe-column>
                  <vxe-column field="reqDept" title="科室" width="80px"></vxe-column>
                  <vxe-column field="sampleType" title="样本类型代码" width="100"></vxe-column>
                  <vxe-column field="feeName" title="申请项目名称" width="280"></vxe-column>
                  <vxe-column field="bedNo" title="床号" width="50px"></vxe-column>
                  <vxe-column field="reqTime" title="申请日期" min-width="120"></vxe-column>
                  <vxe-column field="applicantId" title="申请号" width="120"></vxe-column>
                  <vxe-column field="reqDoctor" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
                  <vxe-column field="amount" title="数量" width="60"></vxe-column>
                  <vxe-column field="adviceGroupId" title="医嘱分组Id" width="100"></vxe-column>
                  <vxe-column field="adviceId" title="医嘱Id" min-width="100"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, inject } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty, formatDateTime } from '@/utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance, List } from 'vxe-table';
// import { id } from 'element-plus/es/locale';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes'; //比例拖拉条
import SelectDataList from '@/components/SelectDataList.vue';
import { AppStore } from '../../../stores/store';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import { setEngine } from 'crypto';
import QuietPrint from '@/components/QuietPrint.vue';
import { initWebSocket, closeWebSocket } from '@/utils/websocketReadCard';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
// 双击配置本机电脑默认病人来源1
let showDefaultVisitTypeModal = false;
let isPrintZYD = ref(false); //是否打印指引单
let isChildren = false;
let loading = ref(false);
let afterloading = ref(false);
let afterPrintBarcodeSpecList: any = reactive([]); //已打印列表
let printBarcodeList: any = reactive([]); //待打印列表

let currentPrintBarcode = reactive({}) as any; //当前选中行
let currentRowIndex = ref(0);
let printParamsObj = ref(null); //打印参数
let deptIds = ref('');
let reportId = ref('');
let barCadeIds = ref('');
let orgId = ref(null);

const printBarcodePreTable = ref(null); //表格ref标记

const newForm = reactive({
  searchValue: '',
  patNo: '',
  beforePatNo: '',
  reqNo: '',
  bedNo: '',
  patType: '',
  patTypeName: '',
  deptNo: [] as any,
  deptNa: '',
  patNa: '',
  IDNo: '',
  reqDateS: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  reqDateE: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});

let tableMenuTop = reactive({
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' },
        {
          code: 'print',
          name: '打印选中',
          prefixIcon: 'vxe-icon-print',
          className: 'my-copy-item'
        },
        {
          code: 'refresh',
          name: '刷新列表',
          prefixIcon: 'vxe-icon-refresh',
          className: 'my-copy-item'
        }
      ]
    ]
  }
});
let tableMenuBottom = reactive({
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' },
        {
          code: 'print',
          name: '打印选中',
          prefixIcon: 'vxe-icon-print',
          className: 'my-copy-item'
        },
        {
          code: 'refresh',
          name: '刷新列表',
          prefixIcon: 'vxe-icon-refresh',
          className: 'my-copy-item'
        }
      ]
    ]
  }
});

// 页面加载时更新报告单元/字典
onMounted(() => {
  orgId = store.userInfo.orgId;
  getReportId();
});

//根据字典ID查询报表
function getReportId() {
  const url = '/api/pubReport/getReportByReportCode';
  proxy.$http
    .get(url, { params: { reportCode: '1754032534504218624' } })
    .then((res: any) => {
      reportId = res.data;
      // workGroupList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// #endregion
function setCurComputerCheckedisPrintZYD() {
  const flag = localStorage.getItem('isPrintZYD');
  if (flag) {
    localStorage.removeItem('isPrintZYD');
    proxy.isPrintZYD = false;
    VXETable.modal.message({ content: '取消配置成功', status: 'warning' });
  } else {
    localStorage.setItem('isPrintZYD', '1');
    proxy.isPrintZYD = true;
    VXETable.modal.message({ content: '配置成功', status: 'success' });
  }
}

//单元格样式
function cellStyle({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'sameSpecCodeBgColor') {
    return { backgroundColor: row.sameSpecCodeBgColor };
  }
}

//单元格背景颜色
function cellClassName({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'isUrgent' && row.isUrgent) {
    return 'bg-red';
  }
  // if (column.property === 'isCatch' && row.isCatch) {
  //   return 'bg-orange';
  // }
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findPrintBarcodeSpecList();
  }
}

let clickColumn = '';

//条码号扫码
function reqNoEnter(e: any, row: any) {
  if (e.$event.code == 'Enter') {
    const $xTable = proxy.$refs.printBarcodePreTable as any;
    const newPrintBarcodeList = $xTable.getTableData().tableData;

    const res = newPrintBarcodeList.filter((p: any) => {
      if (p.sameSpecCodeBgColor == row.sameSpecCodeBgColor) {
        p.reqNo = row.reqNo;
        return p;
      }
    });
    $xTable.setEditCell(res[res.length - 1], clickColumn);
  }
}

const demo1 = reactive({
  tableKeyboardConfig: {
    isArrow: true,
    isDel: true,
    isEnter: true,
    isTab: true,
    isEdit: true,
    editMethod({ row, column }) {
      // console.log('row', row);
      // console.log('column', column);

      const $table = proxy.$refs.printBarcodePreTable;
      $table.setEditCell(row, column);
    }
  } as VxeTablePropTypes.KeyboardConfig
});

//身份证回车事件
function IDNoValueChangeEnter() { }

//读卡按钮
function IdNoFocus() {
  initWebSocket((item) => {
    console.log('item',item);
    const hasName = 'sbkh' in item.data;
    console.log(hasName); // true

    if (hasName) {
      console.log('社保卡');
      //卡号 = item.data.sbkh

      //处理卡号
    
      //findPrintBarcodeSpecList();
      return 
    }

    if (item.code == 0) {
      newForm.IDNo = item.data.sfzh;
      findPrintBarcodeSpecList();
    } else {
      VxeMessage(item.msg, VxeNotifyType.error);
    };

    closeWebSocket();
   
  });
}

// 查询申请列表
function findPrintBarcodeSpecList() {
  loading.value = true;
  printBarcodeList.length = 0;
  const url = '/lab/hisReq/prefabricateBarcode';
  const data = {
    patNo: newForm.patNo,
    beforePatNo: newForm.beforePatNo,
    reqNo: newForm.reqNo,
    bedNo: newForm.bedNo,
    patType: newForm.patType,
    deptNo: newForm.deptNo,
    patNa: newForm.patNa,
    IDNo: newForm.IDNo,
    reqDateS: newForm.reqDateS,
    reqDateE: newForm.reqDateE,
    searchValue: newForm.searchValue
    // scheduleDateBegin: IsEmpty(newForm.scheduleDate)
    //     ? ''
    //     : formatDateTime(newForm.scheduleDate, 'yyyy-MM-dd') + ' 00:00:00',
    // scheduleDateEnd: IsEmpty(newForm.scheduleDate)
    //     ? ''
    //     : formatDateTime(newForm.scheduleDate, 'yyyy-MM-dd') + ' 23:59:59',
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      printBarcodeList.push(...res.data);
      proxy.$nextTick(() => {
        const $xTable = proxy.$refs.printBarcodePreTable as any;
        $xTable.setAllCheckboxRow(true);
        $xTable.updateFooter(); // 在值发生改变时更新表尾合计(一开始获取页面信息时调用计算表尾方法)
      });
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}

//待打印勾选修改,为了勾选一个同医嘱的都勾选和取消
function checkboxStateChange({ checked, row }: any) {
  const $xTable = proxy.$refs.printBarcodePreTable as any;
  const arr = printBarcodeList.filter((e) => {
    return e.sameSpecCodeBgColor == row.sameSpecCodeBgColor;
  });
  if (arr && arr.length > 0) {
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
  }
  //   totalJe = 0;

  //   const sz = printBarcodeList.map((p) => p.totalAmount);
  //   for (let index = 0; index < sz.length; index++) {
  //     const z = sz[index];
  //     if (!IsEmpty(z)) {
  //       totalJe += z;AAA
  //     }
  //   }
  $xTable.updateFooter();
  proxy.$forceUpdate();
}

//待打印行点击
function printBarcodePreRowClick({ row, rowIndex, column }: any) {
  clickColumn = column;
  if (IsEmpty(row)) {
    currentPrintBarcode = {} as any;
    return;
  }
  currentRowIndex = rowIndex;
  currentPrintBarcode = row;
  const xTable = proxy.$refs.printBarcodePreTable as any;
  xTable.setCurrentRow(row);
}

//打印按钮 (准备选中的数据)
function printManyStep1(tableName: any, isAgain = false) {
  const $xTable = proxy.$refs[tableName] as any;
  const selectRows = $xTable.getCheckboxRecords();

  if (!(selectRows && selectRows.length > 0 && selectRows[0])) {
    VxeMessage('请先选中要打印的条码', VxeNotifyType.info);
  } else {
    // const isCatchList = selectRows.filter(item => {
    //     return item.isCatch;
    // });
    // if (isCatchList.length > 0) {
    //     (proxy as any).$XModal.confirm('数据存在问题,是否现在打印?').then(type => {
    //         if (type === 'confirm') {
    //             if (isAgain) {
    //                 printManyStep3(selectRows, isAgain);
    //                 return;
    //             }
    //             printManyStep2(selectRows);
    //         }
    //     });
    // } else {
    //     if (isAgain) {
    //         printManyStep3(selectRows, isAgain);
    //         return;
    //     }
    //     printManyStep2(selectRows);
    // }

    if (isAgain) {
      printManyStep3(selectRows, isAgain);
      return;
    }
    printManyStep2(selectRows);
  }
}

// 打印
function printManyStep2(arr: any) {
  const data = { labHisReqList: arr };
  const url = '/lab/hisReq/barcodePrint';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      barCadeIds = res.data;
      VxeMessage(res.status.msg, VxeNotifyType.success);
      // bacGermFormRef.value?.clearFormData();
      printManyStep3(arr);
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 不是重打的打印之后数据放到重打列表
function printManyStep3(arr: any, isAgain = false) {
  if (!isAgain) {
    const $xTable = proxy.$refs.printBarcodePreTable as any;
    const indexArr = [];
    arr.forEach((element) => {
      const obj = Object.assign({}, element);
      const i = $xTable.getRowIndex(element);
      indexArr.push(i);
      afterPrintBarcodeSpecList.push(obj); //.unshift(obj);
    });
    $xTable.removeCheckboxRow();
  }

  // 调用报表,发送打印任务
  printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'Id', Value: barCadeIds }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };

  //打印导引单
  if (isPrintZYD) {
    // arrList.push({
    //   Id: new Date().valueOf(),
    //   RptId: '指引单.rdlx',
    //   RptParameters: [{ Name: 'Id', Value: ids }]
    // });
  }

  // 清空查询条件
  clearFormConditions();
}

function clearFormConditions() {
  newForm.searchValue = '';
  newForm.patNo = '';
  newForm.beforePatNo = '';
  newForm.reqNo = '';
  newForm.bedNo = '';
  newForm.patType = '';
  newForm.deptNo = '';
  newForm.patNa = '';
  newForm.reqDateS = formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00');
  newForm.reqDateE = formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59');
}
//重打条码
function printAgain() {
  printManyStep1('afterPrintBarcodeTable', true);
}

// 清空已打印
function deleteAllAfterPrintSpecs() {
  afterPrintBarcodeSpecList = [];
}

//已打印列表勾选状态
function afterCheckboxStateChange({ checked, row }: any) {
  const arr = afterPrintBarcodeSpecList.filter((e) => {
    return e.sameSpecCodeBgColor == row.sameSpecCodeBgColor;
  });
  if (arr && arr.length > 0) {
    const $xTable = proxy.$refs.afterPrintBarcodeSpecList as any;
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
  }
}

//待打印条码 合并行
let totalJe = 0;
function footerMethodTop({ columns, data }) {
  const footerData = [
    columns.map((column, _columnIndex = 12) => {
      if (_columnIndex === 12) {
        const $xTable = proxy.$refs.printBarcodePreTable as any;
        const arr = $xTable.getCheckboxRecords();
        const sz = arr.map((p) => {
          return p.price;
        });
        totalJe = 0;
        const newsz = arr.reduce((prev, next) => {
          return prev + next.amount * next.price;
        }, 0);

        totalJe = newsz;
        return `金额合计: ${formatJe(totalJe)}  选中共计: ${arr.length} 项`;
      }
      return null;
    })
  ];

  return footerData;
}

function formatJe(v) {
  if (Number.isNaN(v)) {
    return '';
  }
  return Number(v).toFixed(2);
}

// 组件
//点击选择的那一项受检单位
function SelectRowClick(row) {
  newForm.patTypeName = row.name;
  newForm.patType = row.code;
}

// 清空表单值方法  子组件传递
function clearPatTypeName() {
  newForm.patTypeName = '';
  newForm.patType = '';
}

// 键盘事件删除输入框文字
function sliceHandler() {
  let newStr = newForm.patTypeName.slice(0, -1);
  newForm.patTypeName = newStr;
  let newStr1 = newForm.patType.slice(0, -1);
  newForm.patType = newStr1;
}

// 组件选中事件
function selectRow(row, index) {
  deptIds.value = '';
  newForm.deptNo.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    newForm.deptNo.push(item.code);
    deptIdArr.push(item.id);
  });

  newForm.deptNa = nameArr.join(',');
  deptIds.value = deptIdArr.join(',');
  //instrSampleList[index].itemDictIds = idString;
}
</script>

<style lang="scss" scoped>
#printBarcodePre {
  height: 100%;
  width: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
    }
  }

  .printBarcodePreTable {
    height: calc(100vh - 160px);
  }
}

.custom-checkbox {
  font-size: 16px;
  cursor: pointer;
}

:deep(.vxe-body--row) {
  padding-left: 10px !important;
}
</style>
